// 使用express构建web项目
//1. 导入express
const express = require("express");
// 2. 创建app应用
const app = express();

// 需要（中间件）使用编码处理post请求参数，才可以获取
app.use(express.urlencoded({ extended: true }))
// 将项目中的public目录直接暴露出去，让客户端浏览器可以直接方法（静态资源配置）
app.use(express.static("public")); // 不指定访问前缀

// 3. 设置路由
app.get("/test01", (req, res)=>{
    // 设置运行客户跨域访问
    res.set("Access-Control-Allow-Origin","*");
    res.send("Hello World2!");
})
// ajax的get请求参数处理（求和计算）
app.get("/test02", (req, res) => {
    let m1 = parseFloat(req.query.m1);
    let m2 = parseFloat(req.query.m2);
    res.send(`${m1}+${m2}=${m1+m2}`);
});
// ajax的post请求参数处理（求和计算）
app.post("/test02", (req, res) => {
    let m1 = parseFloat(req.body.m1);
    let m2 = parseFloat(req.body.m2);
    res.send(`${m1}+${m2}=${m1+m2}`);
});
app.get("/test04.html", (req, res)=>{
    res.send("Hello World2!"+new Date().getTime());
    //res.send("Hello World2!");
})

// 响应json数据
app.get("/test05", (req, res)=>{
    // express 框架会在响应时自动补上响应文件类型
    // Content-Type: text/html; charset=utf-8
    // res.send("<h1>Hello World</h1>");

    // 通过res的json方法来响应json数据
    // Content-Type: application/json; charset=utf-8
    const data = [
        {id:"1001",name:"lisi",age:20},
        {id:"1002",name:"王五",age:22},
        {id:"1003",name:"赵六",age:21}
    ];
    res.json(data);
})

// 响应json数据(城市信息的级联响应)
app.get("/test06", (req, res)=>{
    // 接收请求的pid参数，若没有默认为0
    let pid = req.query.pid? req.query.pid : 0;
    // 通过res的json方法来响应json数据
    // Content-Type: application/json; charset=utf-8
    // 初始化的城市信息
    const cityList = [
        {id:1, name:"河北省", pid:0},
        {id:2, name:"黑龙江省", pid:0},
        {id:3, name:"辽宁省", pid:0},
        {id:4, name:"吉林省", pid:0},
        {id:5, name:"张家口", pid:1},
        {id:6, name:"石家庄", pid:1},
        {id:7, name:"邯郸", pid:1},
        {id:8, name:"廊坊", pid:1},
        {id:9, name:"哈尔滨", pid:2},
        {id:10, name:"佳木斯", pid:2},
        {id:11, name:"齐齐哈尔", pid:2},
        {id:12, name:"大连", pid:3},
        {id:13, name:"营口", pid:3},
        {id:14, name:"沈阳", pid:3},
        {id:15, name:"吉林", pid:4},
        {id:16, name:"长春", pid:4},
        {id:17, name:"延边", pid:4}
    ];
    // 通过参数pid获取对应城市信息
    const data = cityList.filter(item => item.pid == pid);
    // json
    res.json(data);
})

// jsonp跨域的请求处理
app.get("/test09", (req, res)=>{
    res.send(`abc("Hello Ajax222!")`);
});

// 4. 监听端口启动服务
app.listen(3000,() => {
    console.log("服务已启动,端口：3000");
});

